package org.carota.pdf;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

/**
 * @author : AnWen
 * @version :1.0
 * @since : 2023-03-29 19:24
 */
public abstract class PdfConfigurer implements Ordered {

    protected PdfProcessor processor;
    protected Boolean isLastNode = false;

    public PdfConfigurer(){
    }

    public PdfConfigurer(PdfProcessor processor) {
        this.processor = processor;
    }


    public PdfProcessor getProcessor() {
        return processor;
    }

    public void setProcessor(PdfProcessor processor) {
        this.processor = processor;
    }

    /**
     * 执行PDF操作
     */
    public abstract void execute();

    /**
     * 执行PDF操作 并关闭阅读器
     */
    public void executeAndClose() {
        execute ();
        processor.close ();
    }


    /**
     * 校验参数
     */
    protected abstract void checkParams();

    public PdfProcessor and() {
        checkParams ();
        return this.processor;
    }



    public boolean isLastNode() {
        return isLastNode;
    }


    public void setLastNode() {
        isLastNode = true;
    }

    /**
     * 校验参数
     *
     * @param module 校验模块
     * @param params 参数
     */
    protected void checkParams(String module, Object... params) {
        List<String> errorList = new ArrayList<> ();
        for (int i = 0; i < params.length; i += 2) {
            checkParam (params[i], (String) params[i + 1], errorList);
        }
        if (!errorList.isEmpty ()) {
            StringJoiner joiner = new StringJoiner (", ", "[", "]");
            joiner.add (String.join (",", errorList));
            throw new PdfException (module, joiner.toString ());
        }
    }

    private void checkParam(Object param, String paramName, List<String> errorList) {
        if (param == null) {
            errorList.add (paramName);
        } else if (param instanceof String && ((String) param).trim ().isEmpty ()) {
            errorList.add (paramName);
        } else if (param instanceof Object[] && ((Object[]) param).length == 0) {
            errorList.add (paramName);
        }
    }

}
